<?php
/**
 * User: Tegic
 * Time: 2018-06-07 14:37:06
 */

namespace app\hander;

use Elasticsearch\ClientBuilder;

class ElasticsearchHander
{
	protected $client;
	protected $index = '';
	protected $type = '';
	
	/**
	 *
	 * ElasticsearchHander constructor.
	 *
	 * @param string $es_host
	 * @param string $index
	 */
	public function __construct($es_host = '', $index = 'article')
	{
		if (!$es_host) {
			$es_host = config('es_host');
		}
		$es_client    = ClientBuilder::create()->setHosts($es_host)->build();
		$this->client = $es_client;
		$this->index  = $index;
		$this->type   = $index;
	}
	
	public function addDocument($id, $body)
	{
		$params = [
			'index' => $this->index,
			'id'    => $id,
			'type'  => $this->type,
			'body'  => $body
		];
		
		$response = $this->client->index($params);
		return $response;
	}
	
	public function create_index($id)
	{
		$indexParams['id']                                     = $id;
		$indexParams['index']                                  = $this->index;
		$indexParams['type']                                   = $this->type;
		$indexParams['body']['settings']['number_of_shards']   = 2;
		$indexParams['body']['settings']['number_of_replicas'] = 0;
		$result                                                = $this->client->create($indexParams);
		return $result;
	}
	
	public function add_document($id, $body)
	{
		$id              = (int) $id;
		$body['id']      = $id;
		$params          = [];
		$params['body']  = $body;
		$params['index'] = $this->index;
		$params['type']  = $this->type;
		$params['id']    = $id;
		$result          = $this->client->index($params);
		return $result;
	}
	
	public function delete_index()
	{
		$deleteParams['index'] = $this->index;
		$result                = $this->client->indices()->delete($deleteParams);
		return $result;
	}
	
	public function delete_document($id)
	{
		$deleteParams          = [];
		$deleteParams['index'] = $this->index;
		$deleteParams['type']  = $this->type;
		$deleteParams['id']    = $id;
		try {
			$result = $this->client->delete($deleteParams);
		} catch (\Exception $e) {
			return true;
		}
		return $result;
	}
	
	public function update_document($id, $body)
	{
		$updateParams          = [];
		$updateParams['index'] = $this->index;
		$updateParams['type']  = $this->type;
		$updateParams['id']    = $id;
		$updateParams['body']  = $body;
		$result                = $this->client->update($updateParams);
		return $result;
	}
	
	public function search($keywords, $input=['page'=>1,'pagesize'=>20], $sort = [])
	{
		$searchParams['index']                                      = $this->index;
		$searchParams['type']                                       = $this->type;
		$searchParams['query']['bool']['should']['match'] ['title'] = $keywords;
		$searchParams['query']['bool']['should']['match'] ['desc']  = $keywords;
		$page                                                       = '';
		$pagesize                                                   = '';
		if (is_array($input)) {
			if (array_key_exists("page", $input)) {
				$page = $input["page"]; //page for offset(es_from);
			}
			if (array_key_exists("pagesize", $input)) {
				$pagesize = $input["pagesize"];    //es_size;
			}
		}
		
		$params = [
			'index' => $this->index,
			'type'  => $this->type,
			'body'  => [
				'query' => [
					'bool' => [
						'should'               => [
							[ 'match_phrase' => [ 'title' => $keywords ] ],
							[ 'match_phrase' => [ 'desc' => $keywords ] ],
						],
						"minimum_should_match" => 1,
					],
				],
				'from'  => ( $page - 1 ) * $pagesize,  // 分页
				'size'  => $pagesize,  // 每页数量
				'sort'  => $sort
			]
		];
		
		$result = $this->client->search($params);
		return $result;
	}
	
	public function get_document($id)
	{
		$getParams          = [];
		$getParams['index'] = $this->index;
		$getParams['type']  = $this->type;
		$getParams['id']    = $id;
		$result             = $this->client->get($getParams);
		return $result;
	}
}